<template>
  <div class="app-container">
    <el-collapse-transition>
      <el-form v-if="openCondition" :model="queryParams" ref="queryForm" :inline="true" label-width="68px">
        <el-form-item label="数据组" prop="groupId">
          <el-select v-model="queryParams.theName" placeholder="请选择数据组" @change="theNameChange" filterable clearable
                     size="small">
            <el-option
              v-for="dict in dataDropDownOptions"
              :key="dict.theName"
              :label="dict.theName"
              :value="dict.theName"
            />
          </el-select>
        </el-form-item>
      </el-form>
    </el-collapse-transition>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="success"
          size="mini"
          @click="handleImport"
          v-hasPermi="['system:data:import']"
        >导入
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:data:export']"
        >导出
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:data:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDeleteGroup"
          v-hasPermi="['system:data:remove']"
        >清除组数据
        </el-button>
      </el-col>
      <el-col :span="1.5" style="float: right">
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        <el-button :type="!openCondition?'success':'info'"
                   :icon="!openCondition?'el-icon-caret-bottom':'el-icon-caret-top'" size="mini"
                   @click="openCondition=!openCondition">{{!openCondition?'展开条件':'收起条件'}}
        </el-button>
      </el-col>
    </el-row>

    <el-table :data="dataList" height="580" @sort-change="handleSortChange">
      <el-table-column label="序号" width="50">
        <template scope="scope">
          <span>{{(queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1}}</span>
        </template>
      </el-table-column>
      <el-table-column label="数据名称" align="center" sortable="custom" prop="theName"/>
      <el-table-column label="手机号" align="center" sortable="custom" prop="phone"/>
      <el-table-column label="创建时间" align="center" sortable="custom" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="创建人" align="center" sortable="custom" prop="creSb.name"/>
      <el-table-column label="操作" align="center" fixed="right" width="180" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-info"
            @click="handleView(scope.row)"
          >详情
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:data:edit']"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:data:remove']"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改数据对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="750px">
      <!-- 修改 -->
      <el-form v-if="this.edit" ref="form" :model="form" :rules="rules" label-width="140px">
        <el-form-item label="数据名称" prop="theName">
          <el-input v-model="form.theName" placeholder="请输入数据名称"/>
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="form.phone" type="number" placeholder="请输入内容"/>
        </el-form-item>
      </el-form>
      <!-- 添加 -->
      <el-form v-if="!this.edit" ref="form" :model="form" :rules="rules" label-width="140px">
        <el-form-item label="数据名称" prop="theName">
          <el-input v-model="form.theName" placeholder="请输入数据名称"/>
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="form.phone" type="number" placeholder="请输入内容"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm" size="mini">确 定</el-button>
        <el-button @click="cancel" size="mini">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 数据详情 -->
    <el-dialog title="数据详情" :visible.sync="viewOpen" width="750px">
      <el-form :inline="true" class="detail-inline" label-width="140px">
        <el-form-item label="数据名称：">
          <input class="bird-view-info-input" disabled :title="viewData.theName" :value="viewData.theName"/>
        </el-form-item>
        <el-form-item style="width: 100%;" label="手机号：">
          <input class="bird-view-info-input" disabled :title="viewData.phone" :value="viewData.phone"/>
        </el-form-item>
        <el-form-item label="创建人：">
          <input class="bird-view-info-input" disabled :title="viewData.creSb && viewData.creSb.name"
                 :value="viewData.creSb && viewData.creSb.name"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="viewOpen = false" size="mini">关 闭</el-button>
      </div>
    </el-dialog>

    <!-- 用户导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px">
      <el-upload ref="upload" :limit="1" accept=".xlsx, .xls" :headers="upload.headers"
                 :action="upload.url" :disabled="upload.isUploading"
                 :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess" :auto-upload="false" drag>
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">
          将文件拖到此处，或
          <em>点击上传</em>
        </div>
        <div class="el-upload__tip" slot="tip">
          <el-link type="info" style="font-size:12px" @click="handleDownload">下载模板</el-link>
        </div>
        <div class="el-upload__tip" style="color:red" slot="tip">提示：仅允许导入“xls”或“xlsx”格式文件！</div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import {addData, delData, delDataGroup, dropDownData, getData, listData, updateData} from "@/api/system/data";
  import {download} from '@/utils/bird'
  import {getToken} from "@/utils/auth";
  import {getUserProfile} from "@/api/system/user";
  import {Loading} from 'element-ui'

  export default {
    data() {
      return {
        loading: undefined,
        // 条件展开
        openCondition: true,
        // 是否修改
        edit: false,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 总条数
        total: 0,
        // 数据表格数据
        dataList: [],
        // 弹出层标题
        title: "",
        // 是否显示详情弹出层
        viewOpen: false,
        // 是否显示弹出层
        open: false,
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          orderByColumn: 'id',
          isAsc: 'desc'
        },
        // 详情参数
        viewData: {},
        // 表单参数
        form: {},
        // 表单校验
        rules: {
          groupId: [
            {required: true, message: "组不能为空", trigger: "blur"}
          ],
          theName: [
            {required: true, message: "数据名称不能为空", trigger: "blur"}
          ],
          phone: [
            {required: true, message: "数据名称不能为空", trigger: "blur"}
          ],
        },
        // 用户导入参数
        upload: {
          // 是否显示弹出层（用户导入）
          open: false,
          // 弹出层标题（用户导入）
          title: "",
          // 是否禁用上传
          isUploading: false,
          // 设置上传的请求头部
          headers: {Authorization: "Bearer " + getToken()},
          // 上传的地址
          url: process.env.VUE_APP_BASE_API + "/system/data/import",
        },
        dataDropDownOptions: [],
      };
    },
    created() {
      this.getList();

      // 接口数据查询
      dropDownData().then(response => {
        this.dataDropDownOptions = response.data;
      });
    },
    methods: {
      /** 查询数据列表 */
      getList() {
        listData(this.queryParams).then(response => {
          this.dataList = response.data.list;
          this.total = response.data.total;
        });
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.resetPropField(this.form);
        this.clearForm('form');
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetPropField(this.queryParams, {pageNum: 1, pageSize: 10, orderByColumn: 'id', isAsc: 'desc'});
        this.handleQuery();
      },
      // 排序改变事件
      handleSortChange(sorter) {
        this.handleSort(this.queryParams, sorter);
        this.getList();
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.id)
        this.single = selection.length != 1
        this.multiple = !selection.length
      },
      /** 详细按钮操作 */
      handleView(row) {
        const id = row.id
        getData(id).then(response => {
          const {data} = response;
          this.viewData = {
            ...data,
          }
          this.viewOpen = true;
        });
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset();
        this.edit = false;
        this.open = true;
        this.title = "添加数据";
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.edit = true;
        this.reset();
        const id = row.id || this.ids
        getData(id).then(response => {
          const {data} = response;
          this.form = {
            ...data,
            groupId: data.groupId && data.groupId.name
          }
          this.open = true;
          this.title = "修改数据";
        });
      },
      /** 提交按钮 */
      submitForm: function () {
        this.$refs["form"].validate(valid => {
          if (valid) {
            if (this.form.id != undefined) {
              updateData(this.form).then(response => {
                this.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              });
            } else {
              addData(this.form).then(response => {
                this.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              });
            }
          }
        });
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const ids = row.id || this.ids;
        this.$confirm('是否确认删除数据数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function () {
          return delData(ids);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        });
      },
      handleDeleteGroup() {
        const theName = this.queryParams.theName;
        this.$prompt('确定要清除"' + theName + '"组的所有数据?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          inputPattern: /\w+/,
          inputErrorMessage: '密码不能为空'
        }).then(function ({value}) {
          return delDataGroup(theName, value);
        }).then(() => {
          this.getList();
          this.msgSuccess("清除成功");
        });
      },
      handleExport() {
        const curQuery = this.queryParams;
        this.$confirm('确定要导出所选择的数据项?', "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function () {
          getUserProfile().then(response => {
            curQuery.userId = response.data.user.id;
            download("/system/data/export", curQuery);
          });
          return
        });
      },
      handleDownload() {
        download("/system/data/download");
      },
      handleImport() {
        this.upload.title = "手机号码导入";
        this.upload.open = true;
        window.setTimeout(() => {
          console.log("延时显示窗口!")
          document.querySelector(".el-upload--text").style.display = "inline"
        }, 1000)
      },
      // 文件上传中处理
      handleFileUploadProgress(event, file, fileList) {
        this.loading = Loading.service({
          lock: true,
          text: '正在处理导入...',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        });
        this.upload.isUploading = true;
      },
      // 文件上传成功处理
      handleFileSuccess(response, file, fileList) {
        this.loading.close();
        this.upload.open = false;
        this.upload.isUploading = false;
        this.$refs.upload.clearFiles();
        this.$alert(response.msg, "导入结果", {dangerouslyUseHTMLString: true});
        this.getList();
      },
      // 提交上传文件
      submitFileForm() {
        this.$refs.upload.submit();
      },
      theNameChange(value) {
        if (value) {
          this.multiple = false;
        } else {
          this.multiple = true;
        }
      }
    }
  };
</script>
